package com.guigu.doc2;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;

import java.io.IOException;

public class ESTest_Doc_Insert_Batch {
    public static void main(String[] args) throws IOException {

        //创建ES客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        //批量插入
        BulkRequest bulkRequest = new BulkRequest();

        //数据
        bulkRequest.add(new IndexRequest().index("user").id("2000").source(XContentType.JSON,"name","李四","age",20,"sex","男"));
        bulkRequest.add(new IndexRequest().index("user").id("2001").source(XContentType.JSON,"name","王五","age",21,"sex","女"));
        bulkRequest.add(new IndexRequest().index("user").id("2002").source(XContentType.JSON,"name","赵六","age",19,"sex","男"));
        bulkRequest.add(new IndexRequest().index("user").id("2003").source(XContentType.JSON,"name","李小四","age",30,"sex","男"));
        bulkRequest.add(new IndexRequest().index("user").id("2004").source(XContentType.JSON,"name","王小五","age",27,"sex","女"));
        bulkRequest.add(new IndexRequest().index("user").id("2005").source(XContentType.JSON,"name","赵小六","age",31,"sex","男"));

        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println(response.getTook());
        System.out.println(response.getItems());

        //关闭ES客户端
        client.close();

    }
}
